<?php

/**
 * Login
 * 登录辅助类
 * UTF-8
 *
 */
class User_Login
{
    public static $error_code_arr = array(
        0 => array('error' => 0, 'msg' => '登录成功'),
        1 => array('error' => 1, 'msg' => '手机验证码错误'),
        2 => array('error' => 2, 'msg' => '手机号没有注册'),
        3 => array('error' => 3, 'msg' => '请填写正确的手机号'),
        4 => array('error' => 4, 'msg' => '密码格式不正确'),
        5 => array('error' => 5, 'msg' => '请勿重复提交'),
        6 => array('error' => 6, 'msg' => '非法注册拒绝'),
        7 => array('error' => 7, 'msg' => '手机号不能为空'),
        8 => array('error' => 8, 'msg' => '两次输入的密码不一致'),
        9 => array('error' => 9, 'msg' => '验证码错误'),
        10 => array('error' => 10, 'msg' => '设备号不能为空'),
        11 => array('error' => 11, 'msg' => '禁止访问用户组'),
    );

    public function __construct()
    {
    }

    // 检查数据
    public function saveLoginData($loginData)
    {
        $device_number = trim($loginData['device_number']);
        if (empty($device_number)) {
            return self::$error_code_arr[10];
        }
        $phoneNum = trim($loginData['mobile']);
        if (empty($phoneNum)) {
            return self::$error_code_arr[7];
        }
        //验证手机号
        $checkPhone = $this->checkPhone($phoneNum);
        if (!$checkPhone) {
            return self::$error_code_arr[3];
        }
        // 判断手机号是否注册
        $member = $this->checkPhoneUse($phoneNum);
        // 禁止访问用户禁止登录
        if ($member['group_id'] == 2) {
            return self::$error_code_arr[11];
        }
        // 更新最后一次登录时间
        $nowTime = time();
        // 登录成功后返回token
        $token = $this->makeToken($member['uid'], $nowTime, $device_number);
        self::$error_code_arr[0]['data']['userInfo'] = $member;
        self::$error_code_arr[0]['data']['token'] = $token;
        return self::$error_code_arr[0];
    }

    // 生成token
    public function makeToken($uid, $nowTime, $device_number)
    {
        StocksFunc_Cachefunc::getInstance()->set('device_number_' . $uid, $device_number, 86400 * 7);
        $token = UserLoginKey::createKey($uid . '&' . $nowTime . '&' . $device_number);
        return $token;
    }

    // 检查用户名是否为空
    public function makeFreshToken($uid, $nowTime, $device_number)
    {
        $token = UserLoginKey::createKey($uid . '&' . $nowTime . '&' . $device_number . '&Fresh');
        return $token;
    }

    // 验证手机号
    public function checkPhone($phoneNum)
    {
        //验证手机号
        if (Validator::Validate($phoneNum, "mobile")) {
            return true;
        }
        // 手机号格式不正确
        return false;
    }

    // 判断手机号有无注册
    public function checkPhoneUse($phoneNum)
    {
        $member = [];
        if ($member) {
            //手机号已经注册
            return $member;
        }
        return false;
    }
}
